// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        // 验证用户权限
        const {
            OPENID
        } = cloud.getWXContext()
        // const userInfo = await db.collection('users').doc(OPENID).get()

        // 准备商品数据
        const goodsData = {
            ipId: event.ipId,
            ipName: event.ipName,
            seriesId: event.seriesId,
            seriesName: event.seriesName,
            productId: event.productId,
            productName: event.productName,
            releaseTime: event.releaseTime,
            goodsName: event.goodsName,
            goodsImage: event.goodsImage,
            goodsPrice: event.goodsPrice,
            sellerName: event.sellerName,
            sellerId: event.sellerId,
            shipAddress: event.shipAddress, 
            shippingFee: event.shippingFee,
            remark: event.remark,
            createTime: db.serverDate(),
            status: event.status || true,
            type: event.type || 'good',
            collectCount: 0,
        }

        // 开始数据库事务
        const transaction = await db.startTransaction()

        try {
            // 插入商品数据
            const goodsResult = await transaction.collection('blindbox_goods').add({
                data: goodsData
            })

            // 更新卖家商品数量
            await transaction.collection('users').where({
                _openid: OPENID
              }).update({
                data: {
                    goodsCount: _.inc(1)
                }
            })

            // 提交事务
            await transaction.commit()

            return {
                success: true,
                message: '商品上传成功',
                data: {
                    goodsId: goodsResult._id
                }
            }
        } catch (e) {
            // 回滚事务
            await transaction.rollback()
            console.error('数据库事务失败', e)
            return {
                success: false,
                message: '商品上传失败',
                error: e
            }
        }
    } catch (e) {
        console.error('云函数执行失败', e)
        return {
            success: false,
            message: '服务器内部错误',
            error: e
        }
    }
}